import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Like, Repository } from "typeorm";
import { CreateEventDto } from "./dto/create-event.dto";
import { Event } from "./entities/event.entity";

@Injectable()
export class EventsService {
  constructor(
    @InjectRepository(Event)
    private readonly eventsService: Repository<Event>
  ) {}

  create(createEventDto: CreateEventDto) {
    return this.eventsService.save(createEventDto);
  }

  findAll() {
    return this.eventsService.find();
  }

  async findAllWithPagination(page: number, limit: number, search?: string) {
    const skip = (page - 1) * limit;

    // 构建查询条件
    let where: any = {};

    // 如果提供了搜索关键字，则添加搜索条件
    if (search) {
      where = [
        { eventName: Like(`%${search}%`) },
        { eventReson: Like(`%${search}%`) },
      ];
    }

    const [data, total] = await this.eventsService.findAndCount({
      where,
      skip,
      take: limit,
      order: {
        createdAt: "DESC", // 按创建时间倒序排列
      },
    });

    return {
      data,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  async findUserEventsWithPagination(
    userId: number,
    page: number,
    size: number,
    filters?: { eventName?: string; eventReson?: string }
  ) {
    const skip = (page - 1) * size;

    // 构建查询条件
    const where: any = { userId };

    // 如果提供了具体的过滤条件，则添加到查询条件中
    if (filters) {
      // 只有当过滤条件不为空时才添加到查询条件中
      if (filters.eventName && filters.eventName.trim() !== "") {
        where.eventName = Like(`%${filters.eventName}%`);
      }
      if (filters.eventReson && filters.eventReson.trim() !== "") {
        where.eventReson = Like(`%${filters.eventReson}%`);
      }
    }

    const [data, total] = await this.eventsService.findAndCount({
      where,
      skip,
      take: size,
      order: {
        createdAt: "DESC", // 按创建时间倒序排列
      },
    });

    return {
      data,
      total,
      page,
      size,
      totalPages: Math.ceil(total / size),
    };
  }

  findOne(id) {
    return this.eventsService.findOne({ where: { eventId: id } });
  }

  remove(id) {
    return this.eventsService.remove(id);
  }
}
